import 'dart:async';

import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_comment.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/model/ab_video.dart';
import 'package:ceramics/pages/main/video/ab_video_home_page.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_report.dart';
import 'package:ceramics/widgets/ab_elevate_button.dart';
import 'package:ceramics/widgets/ab_image.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class ABVideoItemController extends GetxController {
  late final ABVideo model;

  var scrollController = ScrollController();

  ABVideoItemController({required this.model});

  late var scrollComments = <ABComment>[].obs;
  var index = 0.obs;

  @override
  void onInit() {
    super.onInit();
    fetchComment();
  }

  fetchComment() async {
    scrollComments.value = await ABComment.queryForVideo(model.id);
  }
}

class ABVideoItem extends StatelessWidget {

  final ABVideo model;
  final int index;

  ABVideoItem({super.key, required this.model, this.index = 0});

  late final logic = Get.put(
      ABVideoItemController(model: model), tag: model.id.toString());

  @override
  Widget build(BuildContext context) {
    var controller = Get.find<ABVideoHomePageController>();
    return LayoutBuilder(
        builder: (context, constraints) {
          return Stack(
            children: [
              Obx(() {
                print('index: $index, currentIndex: ${controller.currentIndex.value}');
                return (controller.chewieController.value != null &&
                    controller.currentIndex.value == index &&
                    controller.isPlaying.value)
                    ? _buildPlayer()
                    : ABImage(
                    url: logic.model.videoOss?.thumbUrl,
                    width: constraints.maxWidth,
                    height: constraints.maxHeight,
                    fit: BoxFit.cover);
              }),
              Positioned(
                  right: 10,
                  top: constraints.maxHeight / 2 - 50,
                  child: Obx(() {
                    return Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(
                            logic.model.isLiked.value
                                ? 'images/like_video.webp'
                                : 'images/ceramics_42.webp',
                            width: 50)
                            .onTap(() {
                          _handleLike(logic.model);
                        }),
                        Text(logic.model.likeCount.toString(),
                            style: ABStyles.tsWhite14),
                        20.toVerticalBox,
                        Image.asset('images/ceramics_77.webp', scale: 3)
                            .onTap(() {
                          controller.showCommentSheet();
                        }),
                        Obx(() {
                          return Text(
                              logic.model.commentCount.value.toString(),
                              style: ABStyles.tsWhite14);
                        }),
                      ],
                    );
                  })),
              Positioned(
                  left: 10,
                  right: 80,
                  bottom: 150,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildCommentList(),
                      10.toVerticalBox,
                      Row(
                        children: [
                          Stack(children: [
                            ABCircleAvatar(url: logic.model.avatarOss
                                ?.thumbUrl, size: 60),
                            if (!ABSingleton.didFollow(logic.model.userId ??
                                ''))
                              Positioned(
                                  bottom: 0,
                                  left: 0,
                                  right: 0,
                                  child: ABElevateButton(
                                      onPressed: () =>
                                          controller.toggleFollow(
                                              logic.model.userId ?? ''),
                                      style: ElevatedButton.styleFrom(
                                          padding: EdgeInsets.zero,
                                          shape: RoundedRectangleBorder(
                                              borderRadius:
                                              BorderRadius.circular(10))),
                                      child: Text('Follow'.tr,
                                          style: const TextStyle(
                                              fontSize: 12)))
                                      .size(height: 20)),
                          ]),
                          10.toHorizontalBox,
                          Text(logic.model.nickname ?? '',
                              style: ABStyles.tsWhite17Bold),
                        ],
                      ),
                      10.toVerticalBox,
                      Text(
                          logic.model.title ?? '', style: ABStyles.tsWhite14),
                    ],
                  )),
              Obx(() {
                return Visibility(
                  visible: !controller.isPlaying.value,
                  child: Align(
                    alignment: Alignment.center,
                    child: Image.asset('images/ceramics_36.webp', scale: 3)
                        .onTap(() {
                      controller.videoPlayerController?.play();
                    }),
                  ),
                );
              }),
              Obx(() {
                return Visibility(
                  visible: controller.isBuffering.value,
                  child: Align(
                    alignment: Alignment.center,
                    child: CircularProgressIndicator(
                        color: Colors.black.withOpacity(0.5)),
                  ),
                );
              }),
              Positioned(
                top: 60,
                right: 5,
                child: IconButton(
                  icon: const Icon(Icons.more_vert, color: Colors.white),
                  onPressed: () {
                    showMoreReport(logic.model.userId!);
                  },
                ),
              )
            ],
          );
        }
    );
  }

  Widget _buildPlayer() {
    var controller = Get.find<ABVideoHomePageController>();
    return SizedBox.expand(
      child: FittedBox(
          fit: BoxFit.cover,
          child: SizedBox(
              width: 9,
              height: 16,
              child: Chewie(controller: controller.chewieController.value!))),
    );
  }

  void _handleLike(ABVideo model) {
    var controller = Get.find<ABVideoHomePageController>();
    model.isLiked.value = !model.isLiked.value;
    model.isLiked.value ? model.likeCount++ : model.likeCount--;
    controller.dLike.value = !controller.dLike.value;
    controller.handleModel = model;
  }

  Widget _buildCommentList() {
    return Obx(() {
      return ListView.separated(
        padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
        controller: logic.scrollController,
        itemBuilder: (ctx, idx) {
          var model = logic.scrollComments[idx];
          return Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Flexible(
                child: Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 1, vertical: 5),
                  decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                      shape: BoxShape.rectangle,
                      borderRadius: const BorderRadius.all(Radius.circular(50))
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ABCircleAvatar(url: model.avatarOss?.thumbUrl, size: 30)
                          .padOnly(left: 5),
                      10.toHorizontalBox,
                      Text(model.value ?? '', style: ABStyles.tsWhite14)
                          .padOnly(right: 10)
                          .maxWidth(220),
                    ],
                  ),
                ),
              ),
              ConstrainedBox(constraints: const BoxConstraints(minWidth: 10))
            ],
          );
        },
        separatorBuilder: (ctx, idx) {
          return 10.toVerticalBox;
        },
        itemCount: logic.scrollComments.length,
        shrinkWrap: false,
        reverse: true,
      );
    }).size(width: Get.width, height: 200);
  }
}
